package com.garfield.controller;

import com.garfield.entity.User;
import com.garfield.service.UserService;
import com.garfield.utils.VerifyCodeUtils;

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.ResultType;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
//允许跨域
@CrossOrigin
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    //处理用户注册
    @PostMapping("register")
    //@RequestBody使前端axios传的json变成User对象给后端
    public Map<String,Object> register(@RequestBody User user, HttpServletRequest request ,String code){
        log.info("用户信息:[{}]",user.toString());
        log.info("验证码信息:[{}]",code);
        Map<String,Object> map = new HashMap<>();
        try {
            //强制类型转换，将servletContext里存的验证码拿出来，和用户输入的作比较
            String key = (String) request.getServletContext().getAttribute("code");
            //验证码正确，才能进入下一步注册流程
            if(key.equalsIgnoreCase(code)){
                if(user.getSex().equals("m")){
                    user.setSex("男");
                }else if(user.getSex().equals("f")){
                    user.setSex("女");
                }
                userService.register(user);
                map.put("state",true);
                map.put("msg","提示：注册成功!");
            }else{
                throw new RuntimeException("验证码错误!");
            }
        }catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","提示：" + e.getMessage() + " 注册失败！");
        }
        return map;
    }

    //    生成验证码图片
    @GetMapping("getImage")
    public String getImageCode(HttpServletRequest request) throws IOException {
        //使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //将验证码放入servletContext作用域（最大的作用域）
        request.getServletContext().setAttribute("code",code);
        //将验证码转为图片输出
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120,40,byteArrayOutputStream,code);
        //此时s还是普通的base64字符串，前端输出的应该是图片形式
        //String s = Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        //将图片转为base64字符串，并且加上引号里的前缀，使字符串转为base64图片形式输出
        String s = "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        return s;
    }

    //处理用户登录
    @PostMapping("login")
    public Map<String,Object> login(@RequestBody User user){
        log.info("当前用户的信息:[{}]",user.toString());
        Map<String,Object> map = new HashMap<>();
        try{
            User UserDB = userService.login(user);
            map.put("state",true);
            map.put("msg","登陆成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
}
